package com.example.kotlin.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.concurrent.thread

class MyService : Service() {

    val TAG = javaClass.name

    var data = "默认数据"
    override fun onBind(intent: Intent): IBinder? {
        Log.e(TAG, "onBind")

        return object : IMyAidlInterface.Stub() {
            override fun basicTypes(
                anInt: Int,
                aLong: Long,
                aBoolean: Boolean,
                aFloat: Float,
                aDouble: Double,
                aString: String?
            ) {

            }

            override fun setData(data: String?) {
                this@MyService.data = data ?: "null"
                Log.e(TAG, "data:$data")
                CoroutineScope(Dispatchers.Main).launch {
                    Toast.makeText(this@MyService,data,Toast.LENGTH_SHORT).show()
                }

            }


        }
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.e(TAG, "onUnBind")
        return super.onUnbind(intent)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(TAG, "onStartCommand")
        return super.onStartCommand(intent, flags, startId)

    }

    var running = false
    override fun onCreate() {
        super.onCreate()
        Log.e(TAG, "onCreate")

        thread {
            running = true

            while (running) {
                println(data)
                Thread.sleep(1000)

            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy")
        running = false
    }
}
